package com.web.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.web.model.CardLaunchRecord;
import com.web.model.Message;
import com.web.model.Records;
import com.web.model.UserModel;
import com.web.util.WechatRequest;
import org.apache.log4j.Logger;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by reeveslee on 16/6/28.
 */
public class RouteController extends Controller {
    private static final Logger LOGGER = Logger.getLogger(RouteController.class);

    public void auth() {
        String code = getPara("code");
        setAttr("code", code);
        LOGGER.error("code: " + code);

        Map<String, Object> user_info_attr = new HashMap<>();

        Map<String, Object> access_token_map = WechatRequest.accessToken(code);
        if (!"".equals(access_token_map.get("access_token"))) {
            // 用户同意授权
            UserModel userModel = UserModel.userDao.getUserInfo((String) access_token_map.get("openid"));
            if (userModel == null) {
                // 用户未注册
                String openId = (String) access_token_map.get("openid");
                String access_token = (String) access_token_map.get("access_token");
                String refresh_token = (String) access_token_map.get("refresh_token");
                Map<String, Object> user_info_map = WechatRequest.getUserInfo(access_token, openId);
                String name = (String) user_info_map.get("nickname");
                String sex = "男";
                String province = (String) user_info_map.get("province");
                String city = (String) user_info_map.get("city");
                String photo = (String) user_info_map.get("headimgurl");

                long userId = UserModel.userDao.addUser(openId, access_token, refresh_token, name, sex, province, city, photo);
                user_info_attr.put("photo", photo);
                user_info_attr.put("name", name);
                user_info_attr.put("college", "");
                user_info_attr.put("sex", sex);
                user_info_attr.put("wechatAccount", "");
                user_info_attr.put("slogan", "");
                user_info_attr.put("id", userId);
                setAttr("launch_records", null);
                getSession().setAttribute("userId", userId);

            } else {
                // 用户已注册
                user_info_attr.put("id", userModel.get("id"));
                user_info_attr.put("photo", userModel.get("photo"));
                user_info_attr.put("name", userModel.get("name"));
                user_info_attr.put("college", userModel.get("college"));
                user_info_attr.put("sex", userModel.get("sex"));
                user_info_attr.put("wechatAccount", userModel.get("wechatAccount"));
                user_info_attr.put("slogan", userModel.get("slogan"));
                setAttr("launch_records", CardLaunchRecord.cardLaunchRecordDao.getUserLaunchCardRecords(userModel.getLong("id")));
                getSession().setAttribute("userId", userModel.get("id"));
            }

            setAttr("user_info", user_info_attr);
        } else {
            // 用户不同意授权
        }

        gotoMain();
    }

    /**
     * 主页面 ok
     */
    public void gotoMain() {
        if (getSession().getAttribute("userId") == null) {
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx651efc7e955f2b3c&redirect_uri=http://www.kuibutech.com/wechatAuth/route/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
        int userId = (int) (long) getSession().getAttribute("userId");
        setAttr("user_info", UserModel.userDao.findById(userId));
        setAttr("records", Records.recordsDao.getUserRecords(userId));
        setAttr("launch_records", CardLaunchRecord.cardLaunchRecordDao.getUserLaunchCardRecords(userId));

        Map<String, Object> map = new HashMap<>();
        map.put("walk", 0);
        map.put("run", 0);
        map.put("bike", 0);
        map.put("build", 0);
        List<Record> records = Records.recordsDao.getUserCountData(userId);
        for (Record record : records) {
            if ("走路".equals(record.get("type"))) {
                map.replace("walk", new DecimalFormat("#").format(record.get("value")));
            }
            if ("跑步".equals(record.get("type"))) {
                map.replace("run", new DecimalFormat("#.00").format(record.get("value")));
            }
            if ("骑行".equals(record.get("type"))) {
                map.replace("bike", new DecimalFormat("#.00").format(record.get("value")));
            }
            if ("健身".equals(record.get("type"))) {
                map.replace("build", new DecimalFormat("#.0").format(record.get("value")));
            }
        }
        setAttr("count_data", map);
        renderJsp("/my.jsp");
    }

    /**
     * 打卡界面 ok
     */
    public void gotoCard() {
        if (getSession().getAttribute("userId") == null) {
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx651efc7e955f2b3c&redirect_uri=http://www.kuibutech.com/wechatAuth/route/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
        int userId = (int) (long) getSession().getAttribute("userId");
        setAttr("user_info", UserModel.userDao.findById(userId));
        renderJsp("/card.jsp");
    }

    /**
     * 修改资料界面 ok
     */
    public void gotoEditInfo() {
        if (getSession().getAttribute("userId") == null) {
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx651efc7e955f2b3c&redirect_uri=http://www.kuibutech.com/wechatAuth/route/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
        int userId = (int) (long) getSession().getAttribute("userId");
        setAttr("user_info", UserModel.userDao.findById(userId));
        setAttr("records", Records.recordsDao.getUserRecords(userId));
        renderJsp("/editInfo.jsp");
    }

    /**
     * 打卡分享界面 ok
     */
    public void gotoShare() {
        if (getSession().getAttribute("userId") == null) {
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx651efc7e955f2b3c&redirect_uri=http://www.kuibutech.com/wechatAuth/route/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
        int launchCardId = getParaToInt(0);
        int userId = (int) (long) getSession().getAttribute("userId");
        setAttr("userId", userId);
        setAttr("launchCardId", launchCardId);
        setAttr("user_info", UserModel.userDao.findById(userId));
        setAttr("launch_info", CardLaunchRecord.cardLaunchRecordDao.findById(launchCardId));
        setAttr("imgs",CardLaunchRecord.cardLaunchRecordDao.getLaunchImgs(launchCardId));

        renderJsp("/share.jsp");
    }

    /**
     * 公众号二维码关注界面 ok
     */
    public void gotoQRcode() {
        renderJsp("/qrcode.jsp");
    }

    /**
     * 通知界面
     */
    public void gotoMessage() {
        List<Message> messages = Message.messageDao.getMessages();
        setAttr("messages", messages);
        renderJsp("/message.jsp");
    }
}
